<!--菜单与权限-->
<script setup>
import { toRefs, ref, nextTick } from 'vue'
import useDialog from '@/hooks/use-dialog'
import { validate50Words, validate20Words, validate50WordsRequired, validate200Words } from '@/utils/form-validate'
// import { saveMenuPermitMockApi } from '@/api/modules/system/menu-permit-api'
import { saveMenuPermitMockApi } from '@/api/mock-js/system/menu-permit-api'
// import { cloneDeep } from 'lodash-es'

defineOptions({
  name: 'DialogMenuPermit'
})

const modelValue = defineModel({type: Boolean})
const prop = defineProps({
  permissionTypeList: {
    type: Array,
    default: () => ([])
  },
  menuList: {
    type: Array,
    default: () => ([])
  }
})
const {permissionTypeList, menuList} = toRefs(prop)
const emit = defineEmits(['on-close'])

const formData = reactive({
  id: undefined,
  permissionName: '',
  permissionType: 'MENU',
  parentId: 0,
  permissionKey: '',
  permissionPath: '',
  permissionTopPath: '',
  sort: undefined,
  icon: '',
  remarks: ''
})
const {
  formRef,
  title,
  preTitle,
  loadData,
  save,
  saveFlag,
  close,
  setInitData,
  quickSubmit
} = useDialog(emit, formData, modelValue)

const rules = {
  permissionName: {required: true, trigger: 'blur', validator: validate20Words},
  permissionType: {required: true, trigger: 'blur', validator: validate50WordsRequired},
  permissionKeyRequired: {required: true, trigger: 'blur', validator: validate50WordsRequired},
  permissionKey: {trigger: 'blur', validator: validate50Words},
  permissionPath: {required: true, trigger: 'blur', validator: validate50Words},
  remarks: {trigger: 'blur', validator: validate200Words}
}
const parentIdProps = {
  label: 'permissionName',
  value: 'id',
  children: 'children',
  expandTrigger: 'hover',
  emitPath: false,
  checkStrictly: true
}

// 类型获取
const permissionType = ref('MENU')
const handleValidate = (val) => {
  // 如果类型为 表单（FORM）时，icon自动填入 ‘isForm'并禁填，isform用于隐藏其在左侧菜单栏的出现
  if (val === 'FORM') {
    formData.permissionType = 'MENU'
    formData.icon = 'isForm'
  } else {
    formData.permissionType = val
  }
  formRef.value.clearValidate()
}


// 获取子级的所有父级（permissionTopPath）
const findParent = (data, target, result) => {
  for (let item of data) {
    if (item.id === target.id) {
      //将查找到的目标数据加入结果数组中
      //可根据需求unshift(item.id)或unshift(item)
      result.unshift(item)
      return true
    }
    if (item?.children?.length) {
      //根据查找到的结果往上找父级节点
      let isFind = findParent(item.children, target, result)
      if (isFind) {
        result.unshift(item)
        return true
      }
    }
  }
  //走到这说明没找到目标
  return false
}
const handleParentId = (val) => {
  if ( !val) {
    formData.permissionTopPath = ''
    return true
  }
  // 递归获取该节点所有父级
  let result = []
  findParent(menuList.value, {id: val}, result)
  if (result.length) {
    // 第一个父级为该节点的最高级别节点
    formData.permissionTopPath = result[0].permissionPath
  }
}

// 添加子级状态，用于判断‘上级菜单’是否只读
const childFlag = ref(false)
const handleSave = async () => {
  if (formData.permissionType === 'BUTTON') {
    formData.sort = undefined
    formData.icon = ''
  }
  await save?.(saveMenuPermitMockApi, '菜单', '', () => emit('on-close'))
}
// 递归判断formData.id跟menuList的id相同的项，禁选
const recursiveDisabledMenu = (target) => {
  for (let i = 0; i < target.length; i++) {
    if ( !target[i]) continue
    if (target[i].id === formData.id) {
      target[i].disabled = true
    } else {
      target[i].disabled = false
      if (target[i]?.children?.length) {
        recursiveDisabledMenu(target[i].children)
      }
    }
  }
}
onMounted(() => {
  nextTick(() => {
    if (formData.id) {
      recursiveDisabledMenu(menuList.value)
      if (formData.permissionType === 'MENU' && formData.icon === 'isForm') {
        permissionType.value = 'FORM'
      } else {
        permissionType.value = formData.permissionType
      }
    }
  })
})
defineExpose({
  preTitle, title, formData, setInitData, childFlag
})
</script>
<template>
  <DialogForm
      class="dialog-menu-permit"
      :model-value="modelValue"
      :title="`${preTitle}${childFlag?'':'菜单与权限'}${title}`"
      :id="formData.id"
      v-model:saveFlag="saveFlag"
      align-center
      width="720px"
      :loading="loadData.loading"
      @on-save="handleSave"
      @on-close="close"
      @on-cancel="close"
  >
    <ElForm ref="formRef" :model="formData" size="large" v-loading="loadData.loading" :rules="rules" label-width="110px"
            @keyup.enter.prevent="e=>quickSubmit(e,handleSave)">
      <ElFormItem label="菜单/权限名称" prop="roleName">
        <ElInput v-model.trim="formData.permissionName" placeholder="请输入菜单名称"/>
      </ElFormItem>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="类型" prop="permissionType">
            <ElRadioGroup v-model.trim="permissionType" @change="handleValidate">
              <ElRadioButton v-for="{paramValue,paramValueName} in permissionTypeList" :key="paramValue"
                             :label="paramValue">
                {{ paramValueName }}
              </ElRadioButton>
              <ElRadioButton label="FORM">表单</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12" v-if="formData.permissionType==='MENU'">
          <ElFormItem label="前端路径" prop="permissionPath">
            <ElInput v-model.trim="formData.permissionPath" placeholder="请输入前端路径"/>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="权限标识">
            <ElInput v-model.trim="formData.permissionKey" placeholder="请输入权限标识"/>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="上级菜单" prop="parentId">
            <ElCascader class="parent-cascader"
                        v-model="formData.parentId"
                        :props="parentIdProps"
                        :show-all-levels="false"
                        :options="menuList"
                        @change="handleParentId"/>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="父级路径" prop="permissionTopPath">
            <ElInput v-model="formData.permissionTopPath" placeholder="请输入父级路径"/>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow v-if="formData.permissionType === 'MENU'">
        <ElCol :span="12">
          <ElFormItem label="图标" prop="icon">
            <ElInput v-model.trim="formData.icon" :disabled="permissionType === 'FORM'"/>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="菜单排序" prop="sort">
            <ElInputNumber v-model.trim="formData.sort" :min="0"/>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElFormItem label="说明" prop="remarks">
        <ElInput type="textarea" rows="3" v-model.trim="formData.remarks"/>
      </ElFormItem>
    </ElForm>
  </DialogForm>
</template>

